import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter_boost/boost_navigator.dart';
import 'package:flutter_module/api/cooperation_request.dart';
import 'package:flutter_module/common/base/base_page.dart';
import 'package:flutter_module/common/extensions/cached_network_image_extension.dart';
import 'package:flutter_module/core/bridge/native_path.dart';
import 'package:flutter_module/core/flutter_bridge.dart';
import 'package:flutter_module/model/all_tim_info_mo.dart';
import 'package:flutter_module/model/cooperation_detail_mo.dart';
import 'package:flutter_module/page/cooperation/widgets/case_show_container.dart';
import 'package:flutter_module/page/cooperation/widgets/cooperation_banner_container.dart';
import 'package:flutter_module/page/cooperation/widgets/cooperation_title_content_container.dart';
import 'package:flutter_module/page/cooperation/widgets/service_obj_container.dart';
import 'package:flutter_module/routers.dart';
import 'package:flutter_module/style/colors.dart';

import 'widgets/cooperation_intro_item.dart';

/// Create by kyluzoi
/// Date: 2021-08-19
///
/// Description:

class CooperationHomePage extends BaseStateFulWidget {
  CooperationHomePage({required this.params});

  final Map params;

  @override
  BaseState<StatefulWidget> buildState() {
    return _CooperationHomeState();
  }
}

class _CooperationHomeState extends BaseState<CooperationHomePage>
    with BasePage {
  late String? _companyId;

  bool _isShowAll = false;
  bool _isCollect = false;

  CooperationDetailMo? _cooperationDetailMo;
  TimUserMo? _timUserMo;

  ScrollController _scrollController = ScrollController();

  _AnimationButtonBLoC bloc = _AnimationButtonBLoC();

  @override
  String get appBarTitle => "合作服务商详情";

  @override
  void initState() {
    super.initState();
    _companyId = widget.params["companyId"];
    isLoading = true;
    _getCooperationDetails();
  }

  @override
  Widget createView(BuildContext context) {
    print('_CooperationHomeState.createView');
    return SafeArea(
      child: Column(
        children: [
          Flexible(flex: 1, child: _contentArea),
          _buttonContainer
          //button
        ],
      ),
    );
  }

  //内容区域
  get _contentArea {
    List<String>? serviceObjs =
        _cooperationDetailMo?.targetCodeName?.split(",");

    List<CaseListMo> caseDatas = _cooperationDetailMo?.caseList ?? [];

    bool isShowCaseList = caseDatas.isNotEmpty;

    List<Widget> widgets = [
      ScrollableBannerContainer(scrollController: _scrollController, banners: [
        if (_cooperationDetailMo?.kvImage?.isEmpty ?? true) ...[""] else
          ...?_cooperationDetailMo?.kvImage?.split(",")
      ]),
      _headerContainer,
      _divider_10,
      //优惠政策
      if (_cooperationDetailMo?.preferential != null) ...[
        CooperationTitleContainer(
          title: "优惠政策",
          children: [
            Text(
              "${_cooperationDetailMo?.preferential ?? ""}",
              style: _contentTextStyle,
            )
          ],
        ),
        _divider_10
      ],

      //服务商简介
      if (_cooperationDetailMo?.companyProfile != null) ...[
        CooperationIntroItem(
            videoCover: _cooperationDetailMo?.videoImage,
            videoUrl: _cooperationDetailMo?.videoUrl,
            contentStyle: _contentTextStyle,
            content: _cooperationDetailMo?.companyProfile),
        _divider_10,
      ],

      if (_cooperationDetailMo?.serviceScope != null) ...[
        CooperationTitleContainer(title: "服务范围", children: [
          Text(
            "${_cooperationDetailMo?.serviceScope}",
            style: _contentTextStyle,
          ),
        ]),
        _divider_10,
      ],

      // 服务对象
      if (serviceObjs != null && serviceObjs.length > 0) ...[
        _getServiceObj(serviceObjs),
        _divider_10,
      ],
      if (isShowCaseList) CooperationTitleContainer(title: "案例展示"),
    ];

    return CustomScrollView(controller: _scrollController, slivers: [
      SliverList(
          delegate: SliverChildBuilderDelegate((context, index) {
        return widgets[index];
      }, childCount: widgets.length)),

      // 案例展示
      if (isShowCaseList) ...[
        CaseShowContainer(
          datas: caseDatas,
          isShowAll: _isShowAll,
        ),
        if (caseDatas.length > 4)
          SliverFixedExtentList(
              delegate:
                  SliverChildBuilderDelegate((BuildContext context, int index) {
                return InkWell(
                  onTap: () {
                    setState(() {
                      _isShowAll = !_isShowAll;
                    });
                  },
                  child: Container(
                    color: Colors.white,
                    alignment: Alignment.center,
                    child: Text(
                      "全部${_isShowAll ? "收起" : "展开(${caseDatas.length - 4})"}",
                      style:
                          TextStyle(color: ThemeColors.text888, fontSize: 12),
                    ),
                  ),
                );
              }, childCount: 1),
              itemExtent: 60)
      ],
    ]);
  }

// 公司信息
  get _headerContainer => Align(
        heightFactor: 0.8,
        child: Container(
            // 圆角
            height: 138,
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(15),
                    topRight: Radius.circular(15))),
            // 真正的内容部分
            padding: EdgeInsets.only(left: 16, top: 15, bottom: 21, right: 20),
            child: Row(
              children: [
                // icon + 收藏按钮
                SizedBox(
                  width: 80,
                  child: Column(
                    children: [
                      _getIconImg,
                      SizedBox(
                        height: 9,
                      ),
                      //收藏按钮
                      AnimatedBuilder(
                          animation: bloc,
                          builder: (context, _) {
                            Widget loadingWidget = Container(
                              padding: EdgeInsets.only(
                                  left: 8, right: 8, top: 9, bottom: 9),
                              child: LinearProgressIndicator(),
                            );
                            _AnimationBtnState state = bloc.buttonState;
                            return InkWell(
                              onTap: () async {
                                try {
                                  bloc.changeToLoading();
                                  var result =
                                      await _requestCollect(_companyId ?? "");
                                  bloc.changeToSuccess();

                                  setState(() {
                                    _isCollect = result;
                                    if (_isCollect) {
                                      _cooperationDetailMo?.collectCount =
                                          (_cooperationDetailMo?.collectCount ??
                                                  0) +
                                              1;
                                    } else {
                                      _cooperationDetailMo?.collectCount =
                                          (_cooperationDetailMo?.collectCount ??
                                                  1) -
                                              1;
                                    }
                                  });
                                } catch (e) {
                                  bloc.changeToError();
                                }
                              },
                              child: AnimatedContainer(
                                height: 22,
                                width: _isCollect ? 72 : 68,
                                duration: Duration(milliseconds: 600),
                                decoration: BoxDecoration(
                                    color: _isCollect
                                        ? ThemeColors.grayAAA
                                        : ThemeColors.redEF5D5E,
                                    borderRadius: BorderRadius.circular(3)),
                                child: state == _AnimationBtnState.loading
                                    ? loadingWidget
                                    : Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.center,
                                        children: [
                                            if (!_isCollect) ...[
                                              Icon(
                                                Icons.add,
                                                size: 15,
                                                color: Colors.white,
                                              )
                                            ],
                                            Flexible(
                                              flex: 1,
                                              child: Text(
                                                _isCollect ? "取消收藏" : "收藏",
                                                maxLines: 1,
                                                style: TextStyle(
                                                    color: Colors.white,
                                                    fontSize: 10,
                                                    height: 1.4),
                                              ),
                                            ),
                                          ]),
                              ),
                            );
                          })
                    ],
                  ),
                ),
                SizedBox(
                  width: 35,
                ),
                // 公司名 简介等信息...
                _getCompanyInfo
              ],
            )),
      );

// 公司logo
  get _getIconImg {
    var imageRadius = 5.0;
    return Container(
        width: 70,
        height: 70,
        child: ClipRRect(
            borderRadius: BorderRadius.circular(imageRadius),
            child: YFNetworkImage(
              resource: _cooperationDetailMo?.companyLogoUrl,
            )),
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(imageRadius),
            border: Border.all(color: ThemeColors.grayE5E5E5, width: 1)));
  }

// 头部公司信息
  get _getCompanyInfo => Expanded(
          child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 公司名
          Text(
            _cooperationDetailMo?.companyName ?? "",
            style: TextStyle(
                color: ThemeColors.text333,
                fontSize: 16,
                fontWeight: FontWeight.bold),
          ),
          Spacer(
            flex: 1,
          ),
          Text(
            _cooperationDetailMo?.address ?? "",
            style: TextStyle(color: ThemeColors.text888, fontSize: 12),
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
          ),
          Spacer(
            flex: 1,
          ),
          Row(
            children: [
              RichText(
                  text: TextSpan(children: [
                TextSpan(text: "看过"),
                TextSpan(
                    text: " ${_cooperationDetailMo?.actualPageView ?? 0} ",
                    style: TextStyle(
                        color: ThemeColors.text333,
                        fontSize: 15,
                        fontWeight: FontWeight.bold)),
                TextSpan(text: " 次")
              ], style: _contentTextStyle)),
              SizedBox(
                width: 27,
              ),
              RichText(
                  text: TextSpan(children: [
                TextSpan(text: "收藏"),
                TextSpan(
                    text: " ${_cooperationDetailMo?.collectCount ?? 0} ",
                    style: TextStyle(
                        color: ThemeColors.text333,
                        fontSize: 15,
                        fontWeight: FontWeight.bold)),
                TextSpan(text: "次")
              ], style: TextStyle(color: ThemeColors.text888, fontSize: 11)))
            ],
          )
        ],
      ));

// 服务对象
  _getServiceObj(List<String>? obj) {
    return CooperationTitleContainer(
      title: "服务对象",
      children: [
        ServiceObjContainer(
          datas: obj,
          contentTextStyle: _contentTextStyle,
        )
      ],
    );
  }

// 获得按钮区域
  get _buttonContainer => Container(
        height: 50,
        child: Row(
          children: [
            // 服务商主页
            Expanded(
              child: MaterialButton(
                elevation: 0,
                highlightElevation: 0,
                shape: RoundedRectangleBorder(),
                splashColor: Color(0x0),
                height: double.infinity,
                color: Colors.white,
                onPressed: onGoListClick,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Image.asset(
                      "images/common/common_school_course_main.png",
                      width: 16,
                      height: 16,
                    ),
                    Container(
                      margin: EdgeInsets.only(top: 3),
                      child: Text(
                        "服务商主页",
                        style:
                            TextStyle(color: ThemeColors.text888, fontSize: 10),
                      ),
                    )
                  ],
                ),
              ),
              flex: 2,
            ),

            // 联系我们
            Expanded(
                child: MaterialButton(
                  elevation: 0,
                  highlightElevation: 0,
                  shape: RoundedRectangleBorder(),
                  splashColor: Color(0x0),
                  height: double.infinity,
                  color: ThemeColors.redEF5D5E,
                  onPressed: onContactServiceClick,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Image.asset(
                        "images/common/common_celebrity_talk.png",
                        width: 24,
                        height: 24,
                      ),
                      Container(
                        margin: EdgeInsets.only(left: 5),
                        padding: EdgeInsets.only(bottom: 3),
                        child: Text(
                          "联系我们",
                          style: TextStyle(color: Colors.white, fontSize: 14),
                        ),
                      )
                    ],
                  ),
                ),
                flex: 5)
          ],
        ),
      );

// 服务商主页
  void onGoListClick() {
    BoostNavigator.instance.push(CooperationRouters.SERVICE_PROVIDER_LIST);
  }

// 点击联系客服
  void onContactServiceClick() async {
    try {
      if (_timUserMo == null && _cooperationDetailMo != null) {
        GetIMUserRequest getIMUserRequest = new GetIMUserRequest(
            _cooperationDetailMo?.id.toString() ?? "", "7");
        var result = await getIMUserRequest.fire(this);
        _timUserMo = AllTimInfoMo.fromJson(result).contact;
      }
      Map<String, dynamic> params = Map();
      params["timUserId"] = _timUserMo!.identifier;
      params["timName"] = _timUserMo!.nick;
      params["isGroup"] = "false";
      FlutterPlatformBridge.getInstance()
          .goToNative(params.map2Uri(NativePath.app.timChat));
    } catch (e) {}
  }

//请求获取合作服务商详情
  void _getCooperationDetails() async {
    CooperationDetailRequest request = new CooperationDetailRequest();
    request.addQurey("id", _companyId ?? "");
    try {
      var result = await request.fire(this);
      setState(() {
        _cooperationDetailMo = CooperationDetailMo.fromJson(result);
        _isCollect = _cooperationDetailMo?.collectFlag ?? false;
        isLoading = false;
      });
    } catch (e) {
      print("error: $e");
    }
  }

  _requestCollect(String companyId) async {
    RequestCollectCooperative requestCollectCooperative =
        RequestCollectCooperative();
    requestCollectCooperative.bodyParams["id"] = companyId;
    return await requestCollectCooperative.fire(this);
  }

//style
  final _contentTextStyle =
      TextStyle(color: ThemeColors.text888, fontSize: 11, height: 1.7);

  final _divider_10 = SizedBox(
    height: 10,
  );
}

enum _AnimationBtnState {
  normal, //  初始态
  loading, //  加载态
  success, //  加载成功  自行做文本切换
  error, //  网络请求失败等情况导致的加载失败
}

class _AnimationButtonBLoC extends ChangeNotifier {
  _AnimationBtnState buttonState = _AnimationBtnState.normal;

  void changeToLoading() {
    buttonState = _AnimationBtnState.loading;
    notifyListeners();
  }

  void changeToSuccess() {
    buttonState = _AnimationBtnState.success;
    notifyListeners();
  }

  void changeToError() {
    buttonState = _AnimationBtnState.error;
    notifyListeners();
  }
}
